#include "FileTableModel.h"
#include <QtGui/QDesktopWidget>
#include <QtGui/QApplication>
#include <QtCore/QDirIterator>
#include <QtGui/QImageReader>
#include <QtGui/QIcon>
#include <QtCore/QDebug>
//#include "ImgDirLoader.h"
#include <assert.h>
#include "Utility.h"

FileTableModel::FileTableModel(QObject *parent)
: QAbstractTableModel(parent),_filePreviewSize(70,70),_scrollViewWidth(0)
,_currSortFlags(QDir::Name|QDir::IgnoreCase)
{
	_scrollViewWidth=QApplication::desktop()->availableGeometry().width();

	connect (&_thumbsCache,SIGNAL(imageChanged(const QString& )),
					this,SLOT(onImageLoaded(const QString&)));
}

FileTableModel::~FileTableModel()
{
	_thumbsCache.save();
}

int FileTableModel::rowCount ( const QModelIndex & parent  ) const {
	if (_files.count()==0)
		return 0;

	int colCount=columnCount();
	return (_files.count() % colCount ==0) ?_files.count()/colCount:_files.count()/colCount+1;
}

int FileTableModel::columnCount ( const QModelIndex & parent  ) const {
	int col=_scrollViewWidth/_filePreviewSize.width();
	if (col==0)
		return 1;
	else
		return col;
}

int FileTableModel::fileIndexFromModelIndex(const QModelIndex& index) const{
	if (index.isValid()){
		int colCount=columnCount();
		if (colCount>0){
			int idx=(index.row()*colCount+index.column());
			if (idx<_files.size())
				return idx;
		}
	}
	return -1;
}

QVariant FileTableModel::data ( const QModelIndex & index, int role  ) const {
	if (role==Qt::DisplayRole ){
		int idx=fileIndexFromModelIndex(index);
		if (idx>-1){
			const FileItem& fi=_files.at(idx);
			return _thumbsCache.image(fi.fileName);    //_imgDirLoaders[_currRoot]->image(_files.at(idx));
		}
	}else if ( role==FilePathRole){
		int idx=fileIndexFromModelIndex(index);
		if (idx>-1){
			const FileItem& fi=_files.at(idx);
			return _currRoot+"/"+fi.fileName;
		}
	}else if (role==MarkRole){
		int idx=fileIndexFromModelIndex(index);
		if (idx>-1){
			const FileItem& fi=_files.at(idx);
			return fi.isSigned;
		}
	}else if (role==Qt::SizeHintRole){
		return _filePreviewSize;
	}else if (role==Qt::BackgroundRole){
		return Qt::white;
	}else if (role==Qt::ForegroundRole){
		return Qt::black;
	}
	return QVariant();
}

void FileTableModel::setSortFlags(QDir::SortFlags sfs){
	if (_currSortFlags!=sfs){
		_currSortFlags=sfs;
		_files.clear();
		foreach(const QString& file,QDir(_currRoot).entryList(Utility::getImageFileFilters(),QDir::Files,_currSortFlags)){
			_files<<FileItem(file);
		}
		this->reset();
	}
}

void FileTableModel::sortByTime(){
	setSortFlags(QDir::Time|QDir::IgnoreCase);
}

void FileTableModel::sortByName(){
	setSortFlags(QDir::Name|QDir::IgnoreCase);
}

void FileTableModel::sortBySize(){
	setSortFlags(QDir::Size|QDir::IgnoreCase);
}


void FileTableModel::setRootDir(const QString& path){
	if (_currRoot==path)
		return;

	_thumbsCache.save();
	_files.clear();
	foreach(const QString& file,QDir(path).entryList(Utility::getImageFileFilters(),QDir::Files,_currSortFlags)){
		_files<<FileItem(file);
	}
	_thumbsCache.load(path);


	_currRoot=path;
	this->reset();
}

void FileTableModel::setFilePreviewSize(const QSize& size){
	int oldCol=columnCount();
	_filePreviewSize=size;
	if (oldCol!=columnCount())
		this->reset();
}

void FileTableModel::setScrollViewWidth(int v){
	int oldCol=columnCount();
	_scrollViewWidth=v;
	if (oldCol!=columnCount())
		this->reset();
}

void FileTableModel::onImageLoaded(const QString& fileName){
	int idx=_files.indexOf(FileItem(fileName));
	if (idx==-1){
		qDebug()<<"Invalid index of "<<fileName<<"\n";
		return;
	}
	int colCount=columnCount();
	int col=(idx%colCount)/*+colCount-1*/;
	int row=(idx-col)/colCount;

	QModelIndex index=this->index(row,col);
	qDebug()<<"FileTableModel emit dataChanged("<<row<<","<<col<<")\n";
	emit dataChanged(index,index);
}

void FileTableModel::notifyFileRenamed(const QString& name,const QString& newName){
	_files.replace(_files.indexOf(QFileInfo(name).fileName()),QFileInfo(newName).fileName());
	_thumbsCache.notifyFileRenamed(name,newName);
}

void FileTableModel::notifyFileRemoved(const QString& name){
	_files.removeOne(QFileInfo(name).fileName());
	this->reset();
}

void FileTableModel::signItem(const QModelIndex& index){
	int idx=fileIndexFromModelIndex(index);
	if (idx>-1){
		_files[idx].isSigned=true;
		emit dataChanged(index,index);
	}
}

void FileTableModel::unsignItem(const QModelIndex& index){
	int idx=fileIndexFromModelIndex(index);
	if (idx>-1){
		_files[idx].isSigned=false;
		emit dataChanged(index,index);
	}
}

void FileTableModel::signAll(){
	foreach(const FileItem& item,_files){
		const_cast<FileItem&>(item).isSigned=true;
	}
	this->reset();
}

void FileTableModel::unsignAll(){
	foreach(const FileItem& item,_files){
		const_cast<FileItem&>(item).isSigned=false;
	}
	this->reset();
}

QStringList FileTableModel::signedFilesPaths() const{
	QStringList files;
	foreach(const FileItem& item,_files){
		if (item.isSigned){
			files<<(_currRoot+"/"+item.fileName);
		};
	}
	return files;
}
